//
//  ShouHouViewController.m
//  JiuJiuShangCheng
//
//  Created by jiujiukeji on 2018/7/16.
//  Copyright © 2018年 jiujiukeji. All rights reserved.
//

#import "ShouHouViewController.h"
#import "OrderTableViewCell.h"
#import "ShouHouTableViewCell.h"
#import "UITextView+Extension.h"
#import "AddAddressTableViewCell.h"
#import "AddressPickerView.h"
#import "TZTestCell.h"
#import "TZImagePickerController.h"
#import "DPPhotoGroupViewController.h"

@interface ShouHouViewController ()<UITableViewDelegate,UITableViewDataSource,AddressPickerViewDelegate,TZImagePickerControllerDelegate,UICollectionViewDelegate, UICollectionViewDataSource,DPPhotoGroupViewControllerDelegate,UITextFieldDelegate>
{
    NSMutableArray *_selectedAssets;
    BOOL _isSelectOriginalPhoto;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *selectedPhotos;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *filePathArray;

@property (nonatomic, strong) UITextView *textView;

@property (nonatomic, strong) NSMutableArray *fuWuBtnArray;
@property (nonatomic, assign) NSInteger fuWuIndex;
@property (nonatomic, strong) NSMutableArray *pingZhengArray;
@property (nonatomic, assign) NSInteger pingZhengIndex;

@property (nonatomic, strong) UIButton *jiaBtn;
@property (nonatomic, strong) UIButton *jianBtn;
@property (nonatomic, assign) NSInteger num;
@property (nonatomic, strong) UILabel *numLB;

@property (nonatomic ,strong) AddressPickerView *pickerView;
@property (nonatomic, strong) NSMutableDictionary *addressDic;
@property (nonatomic, strong) UITextField *areaLB;
@property (nonatomic, strong) UITextField *nameTF;
@property (nonatomic, strong) UITextField *addressTF;
@property (nonatomic, strong) UITextField *phoneTF;
@property (nonatomic, strong) UITextField *ZipCodeTF;
@property (nonatomic, strong) NSString *province;
@property (nonatomic, strong) NSString *city;
@property (nonatomic, strong) NSString *area;


@end

@implementation ShouHouViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = tableViewBgColor;
    [self loadBaseTitleLable:@"商品售后"];
    self.num = 1;
    self.fuWuIndex = 1; // 服务类型 1 退货 2 换货 3 维修
    self.pingZhengIndex = 1; // 申请凭证 1 发票信息 2 检测报告 3 其它文件
    self.filePathArray = [NSMutableArray array];
    self.addressDic = [NSMutableDictionary dictionary];
    
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.pickerView];
    
    [self getAddressWithOrderNum];
}
#pragma mark - 订单号获取收货地址
- (void)getAddressWithOrderNum
{
    if (self.orderDic[@"ordersId"]) {
        NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
        [MBProgressHUD showMessage:nil toView:self.view];
        [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/aftersale.ashx?action=orderaddress&companyid=%@&code=%@&timestamp=%@&ordersid=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],self.orderDic[@"ordersId"]] parameters:nil success:^(id responseObject) {
            [MBProgressHUD hideHUDForView:self.view];
            
            if ([responseObject[@"status"] intValue] == 1) {
                
                [self.addressDic setObject:responseObject[@"ReceiptName"] forKey:@"ReceiptName"];
                [self.addressDic setObject:responseObject[@"ReceiptPhone"] forKey:@"ReceiptPhone"];
                [self.addressDic setObject:responseObject[@"ReciptZipCode"] forKey:@"ReciptZipCode"];
                [self.addressDic setObject:responseObject[@"addressArea"] forKey:@"addressArea"];
                [self.addressDic setObject:responseObject[@"addressCity"] forKey:@"addressCity"];
                [self.addressDic setObject:responseObject[@"addressProvince"] forKey:@"addressProvince"];
                [self.addressDic setObject:responseObject[@"addressXX"] forKey:@"addressXX"];
                
                [self.tableView reloadData];
            } else {
                [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
            }
            
        } failure:^(NSError *error) {
            [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
            
        }];
    }
}
#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 7;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 6) {
        return 5;
    } else {
        return 1;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        OrderTableViewCell *cell = [[OrderTableViewCell alloc] init];
        cell.contentView.backgroundColor = UIColorWhite;
        // 赋值
        if (self.orderDic) {
            NSArray *array = self.orderDic[@"OrderGoodsList"];
            NSDictionary *dic = array[self.goodsIndex];
            [cell.goodsImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http:%@",dic[@"CartImg"]]] placeholderImage:UIImageNamed(@"placeholder")];
            cell.goodsTitleLB.text = dic[@"CommodityName"];
            cell.priceLB.text = [NSString stringWithFormat:@"￥%.2f",[dic[@"CommodityZPrice"] floatValue]];
            cell.describeLB.text = dic[@"CommodityProperty"];
            cell.numLB.text = [NSString stringWithFormat:@"×%@",dic[@"CommodityNumber"]];
        }
        cell.selectionStyle = NO;
        return cell;
    } else if (indexPath.section == 1 || indexPath.section == 3) {
        ShouHouTableViewCell *cell = [[ShouHouTableViewCell alloc] init];
        if (indexPath.section == 1) {
            [cell.btn1 setTitle:@"退货" forState:(UIControlStateNormal)];
            [cell.btn2 setTitle:@"换货" forState:(UIControlStateNormal)];
            [cell.btn3 setTitle:@"维修" forState:(UIControlStateNormal)];
            
            self.fuWuBtnArray = [NSMutableArray array];
            [self.fuWuBtnArray addObject:cell.btn1];
            [self.fuWuBtnArray addObject:cell.btn2];
            [self.fuWuBtnArray addObject:cell.btn3];
            cell.btn1.tag = 1;
            cell.btn2.tag = 2;
            cell.btn3.tag = 3;
            [cell.btn1 addTarget:self action:@selector(fuWuSelect:) forControlEvents:(UIControlEventTouchUpInside)];
            [cell.btn2 addTarget:self action:@selector(fuWuSelect:) forControlEvents:(UIControlEventTouchUpInside)];
            [cell.btn3 addTarget:self action:@selector(fuWuSelect:) forControlEvents:(UIControlEventTouchUpInside)];
            for (UIButton *button in self.fuWuBtnArray) {
                if (self.fuWuIndex == button.tag) {
                    [button setBackgroundImage:[UIImage createImageWithColor:navBarColor] forState:UIControlStateNormal];
                    [button setTitleColor:UIColorWhite forState:(UIControlStateNormal)];
                } else {
                    [button setBackgroundImage:[UIImage createImageWithColor:kClearColor] forState:UIControlStateNormal];
                    [button setTitleColor:UIColorFromRGB(0x909090) forState:(UIControlStateNormal)];
                }
            }
            
        } else {
            [cell.btn1 setTitle:@"我有发票" forState:(UIControlStateNormal)];
            [cell.btn2 setTitle:@"检测报告" forState:(UIControlStateNormal)];
            [cell.btn3 setTitle:@"其他文件" forState:(UIControlStateNormal)];
            
            self.pingZhengArray = [NSMutableArray array];
            [self.pingZhengArray addObject:cell.btn1];
            [self.pingZhengArray addObject:cell.btn2];
            [self.pingZhengArray addObject:cell.btn3];
            cell.btn1.tag = 1;
            cell.btn2.tag = 2;
            cell.btn3.tag = 3;
            [cell.btn1 addTarget:self action:@selector(pingZhengSelect:) forControlEvents:(UIControlEventTouchUpInside)];
            [cell.btn2 addTarget:self action:@selector(pingZhengSelect:) forControlEvents:(UIControlEventTouchUpInside)];
            [cell.btn3 addTarget:self action:@selector(pingZhengSelect:) forControlEvents:(UIControlEventTouchUpInside)];
            for (UIButton *button in self.pingZhengArray) {
                if (self.pingZhengIndex == button.tag) {
                    [button setBackgroundImage:[UIImage createImageWithColor:navBarColor] forState:UIControlStateNormal];
                    [button setTitleColor:UIColorWhite forState:(UIControlStateNormal)];
                } else {
                    [button setBackgroundImage:[UIImage createImageWithColor:kClearColor] forState:UIControlStateNormal];
                    [button setTitleColor:UIColorFromRGB(0x909090) forState:(UIControlStateNormal)];
                }
            }
        }
        cell.selectionStyle = NO;
        return cell;
    } else if (indexPath.section == 6) {
        // 地址
        AddAddressTableViewCell *cell = [[AddAddressTableViewCell alloc] init];
        NSArray *array = @[@"收货人：",@"手机号码：",@"所在地区：",@"详细地址：",@"邮政编码："];
        NSArray *array1 = @[@"请输入收货人姓名",@"请输入手机号码",@"请选择地区",@"街道、楼牌号等",@"6位邮政编码"];
        cell.leftLB.text = array[indexPath.row];
        cell.textField.placeholder = array1[indexPath.row];
        cell.textField.tag = indexPath.row;
        cell.textField.delegate = self;
        if (indexPath.row == 0) {
            self.nameTF = cell.textField;
            if (self.addressDic) {
                self.nameTF.text = self.addressDic[@"ReceiptName"];
            }
        } else if (indexPath.row == 1) {
            self.phoneTF = cell.textField;
            if (self.addressDic) {
                self.phoneTF.text = self.addressDic[@"ReceiptPhone"];
            }
        } else if (indexPath.row == 2) {
            cell.textField.enabled = NO;
            self.areaLB = cell.textField;
            cell.arrow.hidden = NO;
            if (self.addressDic) {
                self.areaLB.text = [NSString stringWithFormat:@"%@ %@ %@",self.addressDic[@"addressProvince"],self.addressDic[@"addressCity"],self.addressDic[@"addressArea"]];
                self.province = self.addressDic[@"addressProvince"];
                self.city = self.addressDic[@"addressCity"];
                self.area = self.addressDic[@"addressArea"];
            }
        } else if (indexPath.row == 3) {
            self.addressTF = cell.textField;
            if (self.addressDic) {
                self.addressTF.text = self.addressDic[@"addressXX"];
            }
        } else {
            self.ZipCodeTF = cell.textField;
            if (self.addressDic) {
                self.ZipCodeTF.text = self.addressDic[@"ReciptZipCode"];
            }
        }
        cell.selectionStyle = NO;
        return cell;
    } else {
        UITableViewCell *cell = [[UITableViewCell alloc] init];
        if (indexPath.section == 2) {
            // 申请数量
            UIImageView *editImg = [[UIImageView alloc] init];
            editImg.image = UIImageNamed(@"numEditImg");
            [editImg sizeToFit];
            [cell.contentView addSubview:editImg];
            [editImg mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(cell.contentView).offset(rateWidth(25));
                make.centerY.equalTo(cell.contentView);
            }];
            editImg.userInteractionEnabled = YES;
            
            UILabel *numLB = [UILabel labelWithText:[NSString stringWithFormat:@"%ld",self.num] textColor:UIColorFromRGB(0x666666) fontSize:13];
            [numLB sizeToFit];
            [editImg addSubview:numLB];
            [numLB mas_makeConstraints:^(MASConstraintMaker *make) {
                make.center.equalTo(editImg);
            }];
            self.numLB = numLB;
            
            self.jiaBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
            [cell.contentView addSubview:_jiaBtn];
            [_jiaBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_offset(CGSizeMake(30, 50));
                make.centerX.equalTo(editImg.mas_right);
                make.centerY.equalTo(editImg);
            }];
            self.jianBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
            [cell.contentView addSubview:_jianBtn];
            [_jianBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_offset(CGSizeMake(30, 50));
                make.centerX.equalTo(editImg.mas_left);
                make.centerY.equalTo(editImg);
            }];
            [_jiaBtn addTarget:self action:@selector(jiaAction) forControlEvents:(UIControlEventTouchUpInside)];
            [_jianBtn addTarget:self action:@selector(jianAction) forControlEvents:(UIControlEventTouchUpInside)];
            
        } else if (indexPath.section == 4) {
            // 问题描述
            UITextView *textView = [[UITextView alloc] init];
            [textView setBackgroundColor:UIColorWhite];
            [cell.contentView addSubview:textView];
            //模仿cell复用
            [textView setPlaceholderWithText:@"长度在1-300字之间" Color:[UIColor lightGrayColor]];
            textView.font = [UIFont systemFontOfSize:15];
            self.textView = textView;
            [textView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(cell.contentView).offset(rateWidth(25));
                make.right.equalTo(cell.contentView).offset(-rateWidth(25));
                make.top.equalTo(cell.contentView).offset(rateHeight(25));
                make.bottom.equalTo(cell.contentView).offset(-rateHeight(25));
            }];
            
        } else if (indexPath.section == 5) {
            // 上传凭证
            [cell addSubview:self.collectionView];
            [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(cell).offset(rateWidth(54));
                make.top.equalTo(cell).offset(rateHeight(37));
                make.right.equalTo(cell).offset(-rateWidth(50));
                make.height.equalTo(@(rateHeight(180)));
            }];
        }
        cell.selectionStyle = NO;
        return cell;
    }
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    switch (textField.tag) {
        case 0:
            [self.addressDic setObject:textField.text forKey:@"ReceiptName"];
            break;
        case 1:
            [self.addressDic setObject:textField.text forKey:@"ReceiptPhone"];
            break;
        case 3:
            [self.addressDic setObject:textField.text forKey:@"addressXX"];
            break;
        case 4:
            [self.addressDic setObject:textField.text forKey:@"ReciptZipCode"];
            break;
        default:
            break;
    }
}
- (void)jiaAction
{
    NSArray *array = self.orderDic[@"OrderGoodsList"];
    NSDictionary *dic = array[self.goodsIndex];
    if (self.num < [dic[@"CommodityNumber"] intValue]) {
        self.num++;
        self.numLB.text = [NSString stringWithFormat:@"%ld",self.num];
    }
}
- (void)jianAction
{
    if (self.num>1) {
        self.num--;
        self.numLB.text = [NSString stringWithFormat:@"%ld",self.num];
    }
}
#pragma mark - 服务类型
- (void)fuWuSelect:(UIButton *)btn
{
    self.fuWuIndex = btn.tag;
    for (UIButton *button in self.fuWuBtnArray) {
        if (btn == button) {
            [button setBackgroundImage:[UIImage createImageWithColor:navBarColor] forState:UIControlStateNormal];
            [button setTitleColor:UIColorWhite forState:(UIControlStateNormal)];
        } else {
            [button setBackgroundImage:[UIImage createImageWithColor:kClearColor] forState:UIControlStateNormal];
            [button setTitleColor:UIColorFromRGB(0x909090) forState:(UIControlStateNormal)];
        }
    }
}
#pragma mark - 申请凭证
- (void)pingZhengSelect:(UIButton *)btn
{
    self.pingZhengIndex = btn.tag;
    for (UIButton *button in self.pingZhengArray) {
        if (btn == button) {
            [button setBackgroundImage:[UIImage createImageWithColor:navBarColor] forState:UIControlStateNormal];
            [button setTitleColor:UIColorWhite forState:(UIControlStateNormal)];
        } else {
            [button setBackgroundImage:[UIImage createImageWithColor:kClearColor] forState:UIControlStateNormal];
            [button setTitleColor:UIColorFromRGB(0x909090) forState:(UIControlStateNormal)];
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return rateHeight(210);
    } else if (indexPath.section == 1 || indexPath.section == 2 || indexPath.section == 3) {
        return rateHeight(110);
    } else if (indexPath.section == 4) {
        return rateHeight(240);
    } else if (indexPath.section == 5) {
        return rateHeight(190);
    } else {
        return rateHeight(85);
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return rateHeight(70);
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 6) {
        return rateHeight(200);
    } else {
        return 0.01;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *bgV = [[UIView alloc] init];
    bgV.backgroundColor = tableViewBgColor;
    if (section == 0) {
        UILabel *label = [UILabel labelWithText:[NSString stringWithFormat:@"订单号：%@",self.orderDic[@"ordersNumber"]] textColor:UIColorFromRGB(0x909090) fontSize:13];
        [label sizeToFit];
        [bgV addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(bgV);
            make.left.equalTo(bgV).offset(rateWidth(25));
        }];
    } else {
        NSArray *array = @[@"服务类型",@"申请数量",@"申请凭据",@"问题描述",@"上传凭证",@"联系地址"];
        UILabel *label = [UILabel labelWithText:array[section-1] textColor:UIColorFromRGB(0x323232) fontSize:15];
        [label sizeToFit];
        [bgV addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@(rateWidth(25)));
            make.centerY.equalTo(bgV);
        }];
    }
    return bgV;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 6) {
        UIView *bgV = [[UIView alloc] init];
        bgV.backgroundColor = tableViewBgColor;
        
        UIButton *btn = [UIButton buttonWithTitle:@"提交" fontSize:15 titleColor:UIColorWhite background:navBarColor cornerRadius:3];
        [bgV addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_offset(CGSizeMake(rateWidth(600), rateHeight(70)));
            make.center.equalTo(bgV);
        }];
        [btn addTarget:self action:@selector(tiJiaoAction) forControlEvents:(UIControlEventTouchUpInside)];
        
        return bgV;
    } else {
        return nil;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 6 && indexPath.row == 2) {
        // 选择地区
        [self selectArea];
    }
}
- (void)selectArea
{
    WeakSelf
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.5 animations:^{
        
        [UIView beginAnimations:@"move" context:nil];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationDelegate:self];
        //改变它的frame的x,y的值
        weakSelf.pickerView.frame = CGRectMake(0, kScreenHeight-200, kScreenWidth, 200);
        [UIView commitAnimations];
    }];
}
#pragma mark - AddressPickerViewDelegate
- (void)cancelBtnClick
{
    WeakSelf
    [UIView animateWithDuration:0.5 animations:^{
        
        [UIView beginAnimations:@"move" context:nil];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationDelegate:self];
        //改变它的frame的x,y的值
        weakSelf.pickerView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 200);
        [UIView commitAnimations];
    }];
}
- (void)sureBtnClickReturnProvince:(NSString *)province City:(NSString *)city Area:(NSString *)area
{
    WeakSelf
    self.areaLB.text = [NSString stringWithFormat:@"%@ %@ %@",province,city,area];
    self.province = province;
    self.city = city;
    self.area = area;
    [self.addressDic setObject:province forKey:@"addressProvince"];
    [self.addressDic setObject:city forKey:@"addressCity"];
    [self.addressDic setObject:area forKey:@"addressArea"];
    [UIView animateWithDuration:0.5 animations:^{
        
        [UIView beginAnimations:@"move" context:nil];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationDelegate:self];
        //改变它的frame的x,y的值
        weakSelf.pickerView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 200);
        [UIView commitAnimations];
    }];
}
- (AddressPickerView *)pickerView{
    if (!_pickerView) {
        _pickerView = [[AddressPickerView alloc]initWithFrame:CGRectMake(0, kScreenHeight , kScreenWidth, 200)];
        _pickerView.delegate = self;
    }
    return _pickerView;
}
#pragma mark - 提交
- (void)tiJiaoAction
{
    if (self.selectedPhotos) {
        for (UIImage *img in self.selectedPhotos) {
            [self uploadImg:img];
        }
    } else {
        [self faBu];
    }
}
- (void)faBu
{
    if (self.orderDic) {
        NSArray *array = self.orderDic[@"OrderGoodsList"];
        NSDictionary *dic = array[self.goodsIndex];
        NSLog(@"filePath-------%@",[self.filePathArray componentsJoinedByString:@"|"]);
        NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
        [MBProgressHUD showMessage:nil toView:self.view];
        [TFNetworking postWithURLString:[NSString stringWithFormat:@"%@/api/json/member/aftersale.ashx?action=addaftersale&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:@{@"cartid":dic[@"CartId"],@"commodityid":dic[@"commodityId"],@"ordersid":self.orderDic[@"ordersId"],@"repairstype":[NSString stringWithFormat:@"%ld",(long)self.fuWuIndex],@"repairsnumber":[NSString stringWithFormat:@"%ld",(long)self.num],@"repairsproof":[NSString stringWithFormat:@"%ld",(long)self.pingZhengIndex],@"repairscontent":self.textView.text,@"repairsimages":[self.filePathArray componentsJoinedByString:@"|"],@"repairsname":self.nameTF.text,@"repairsphone":self.phoneTF.text,@"Receiptaddress":[NSString stringWithFormat:@"%@%@%@%@",self.province,self.city,self.area,self.addressTF.text],@"repairszipcode":_ZipCodeTF.text} success:^(id responseObject) {
            [MBProgressHUD hideHUDForView:self.view];
            if (responseObject) {
                [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
                if ([responseObject[@"status"] intValue] == 1) {
                    [self.navigationController popViewControllerAnimated:YES];
                    
                }
            }
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
            [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        }];
    }
}
#pragma mark - 上传图片
- (void)uploadImg:(UIImage *)image
{
    if (image) {
        [MBProgressHUD showMessage:@"" toView:self.view];
        //1.创建管理者对象
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html", @"application/javascript", @"text/js",@"application/xml", nil];
        //2.上传文件
        NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
        [manager POST:[NSString stringWithFormat:@"%@/api/json/upload/upload.ashx?action=memberimages&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            [MBProgressHUD hideHUDForView:self.view];
            //上传文件参数
            if (image) {
                // 产品图片
                NSData *pictureData = UIImageJPEGRepresentation(image, 0.5);
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                formatter.dateFormat = @"yyMMddHHmmss";
                NSString *fileName = [formatter stringFromDate:[NSDate date]];
                NSString *nameStr = @"filePath"; // 参数名(一定不能写错)
                [formData appendPartWithFileData:pictureData name:nameStr fileName:[NSString stringWithFormat:@"image%@.jpg", fileName] mimeType:@"image/jpeg"];
            }
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            //打印上传进度
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //请求成功
            NSLog(@"-----%@", responseObject);
            [self.filePathArray addObject:responseObject[@"data"]];
            NSLog(@"----%@ -----  %@",self.filePathArray,self.selectedPhotos);
            if (self.filePathArray.count == self.selectedPhotos.count) {
                [self faBu];
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //请求失败
            [TFHUD addRemindHUD:self.view message:@"保存失败"];
            NSLog(@"%@",error);
        }];
    }
}
#pragma mark - 选择图片
- (void)selectImages {
    DPPhotoGroupViewController *controller = [[DPPhotoGroupViewController alloc] init];
    controller.maxSelectionCount = 9;
    controller.delegate = self;
    [self presentViewController:[[UINavigationController alloc] initWithRootViewController:controller] animated:YES completion:nil];
}
#pragma mark - DPPhotoGroupViewControllerDelegate
- (void)didSelectPhotos:(NSMutableArray *)photos {
    NSLog(@"%@", photos);
}

#pragma mark - collectionView dataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.selectedPhotos.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TZTestCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZTestCell" forIndexPath:indexPath];
    cell.videoImageView.hidden = YES;
    if (indexPath.row == _selectedPhotos.count) {
        cell.imageView.image = [UIImage imageNamed:@"xiangjishouhou"];
        cell.deleteBtn.hidden = YES;
        cell.gifLable.hidden = YES;
    } else {
        cell.imageView.image = _selectedPhotos[indexPath.row];
        cell.asset = _selectedAssets[indexPath.row];
        cell.deleteBtn.hidden = NO;
    }
    cell.contentView.backgroundColor = kClearColor;
    cell.gifLable.hidden = YES;
    cell.deleteBtn.tag = indexPath.row;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClik:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
#pragma mark - Click Event
- (void)deleteBtnClik:(UIButton *)sender {
    [_selectedPhotos removeObjectAtIndex:sender.tag];
    [_selectedAssets removeObjectAtIndex:sender.tag];
    
    [_collectionView performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:sender.tag inSection:0];
        [_collectionView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        [_collectionView reloadData];
    }];
}
#pragma mark - collectionView delegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == _selectedPhotos.count) {
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 columnNumber:3 delegate:self pushPhotoPickerVc:YES];
        // 1.设置目前已经选中的图片数组
        imagePickerVc.selectedAssets = _selectedAssets; // 目前已经选中的图片数组
        [self presentViewController:imagePickerVc animated:YES completion:nil];
    } else
    {
        [_selectedPhotos removeObjectAtIndex:indexPath.row];
        [_selectedAssets removeObjectAtIndex:indexPath.row];
        
        [_collectionView performBatchUpdates:^{
            [_collectionView deleteItemsAtIndexPaths:@[indexPath]];
        } completion:^(BOOL finished) {
            [_collectionView reloadData];
        }];
        //        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_selectedAssets selectedPhotos:_selectedPhotos index:indexPath.row];
        //        //            imagePickerVc.maxImagesCount = self.maxCountTF.text.integerValue;
        //        //            imagePickerVc.allowPickingOriginalPhoto = self.allowPickingOriginalPhotoSwitch.isOn;
        //        imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
        //        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        //            _selectedPhotos = [NSMutableArray arrayWithArray:photos];
        //            _selectedAssets = [NSMutableArray arrayWithArray:assets];
        //            _isSelectOriginalPhoto = isSelectOriginalPhoto;
        //            [_collectionView reloadData];
        //            _collectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (15 + rateHeight(120)));
        //        }];
        //        [self presentViewController:imagePickerVc animated:YES completion:nil];
    }
}
#pragma mark - TZImagePickerControllerDelegate
/// 用户点击了取消
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
    // NSLog(@"cancel");
}

// 这个照片选择器会自己dismiss，当选择器dismiss的时候，会执行下面的代理方法
// 如果isSelectOriginalPhoto为YES，表明用户选择了原图
// 你可以通过一个asset获得原图，通过这个方法：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
// photos数组里的UIImage对象，默认是828像素宽，你可以通过设置photoWidth属性的值来改变它
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    _selectedPhotos = [NSMutableArray arrayWithArray:photos];
    _selectedAssets = [NSMutableArray arrayWithArray:assets];
    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    [_collectionView reloadData];
    // _collectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
    
    // 1.打印图片名字
    //    [self printAssetsName:assets];
}

// 如果用户选择了一个视频，下面的handle会被执行
// 如果系统版本大于iOS8，asset是PHAsset类的对象，否则是ALAsset类的对象
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(id)asset {
    _selectedPhotos = [NSMutableArray arrayWithArray:@[coverImage]];
    _selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
    [_collectionView reloadData];
}

// 如果用户选择了一个gif图片，下面的handle会被执行
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingGifImage:(UIImage *)animatedImage sourceAssets:(id)asset {
    _selectedPhotos = [NSMutableArray arrayWithArray:@[animatedImage]];
    _selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
    [_collectionView reloadData];
}
- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.itemSize = CGSizeMake(rateWidth(120), rateWidth(120));
        flowLayout.minimumInteritemSpacing = 15;
        flowLayout.minimumLineSpacing = 15;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, rateWidth(40), rateHeight(200)) collectionViewLayout:flowLayout];
        _collectionView.alwaysBounceVertical = YES;
        _collectionView.backgroundColor = kClearColor;
        _collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        [_collectionView registerClass:[TZTestCell class] forCellWithReuseIdentifier:@"TZTestCell"];
    }
    return _collectionView;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, kScreenWidth, kScreenHeight-SafeAreaTopHeight-SafeAreaBottomHeight) style:(UITableViewStyleGrouped)];
        _tableView.backgroundColor = UIColorFromRGB(0xf5f5f5);
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
    }
    return _tableView;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
